package com.zj.framework.httpclient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zj.framework.excel.ExcelUtil;
import com.zj.framework.excel.usermodel.ExcelData;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.util.*;

/**
 * @author xi.yang(xi.yang@downjoy.com)
 * @create 2018-05-29 下午 3:24
 **/
public class ExportPid {
    private static final int CONNECTION_TIMEOUT = 5 * 1000;

    private static final int REQUEST_TIMEOUT = 10 * 1000;

    public static void main(String[] args) {
        Map<String,String> cookies = getCookies();
        Map<String, String> nvps = new HashMap<>();
        nvps.put("spm","a219t.7900221/1.1998910419.dbb742793.3d7c75a5d2lngA");
        nvps.put("tab","2");
        nvps.put("toPage","1");
        nvps.put("perPageSize","40");
        nvps.put("gcid","7");
        nvps.put("t","1527584715011");
        nvps.put("pvid","60_221.237.158.184_516_1527649899037");
        nvps.put("_tb_token_","eb374509b6e35");
        nvps.put("_input_charset","utf-8");
        List<Pid> allPids = new ArrayList<>();
        for (int i = 1; i < 2; i++) {
            nvps.put("toPage",""+i);
            nvps.put("t",System.currentTimeMillis()+"");
            List<Pid> result = getPids(cookies, nvps);
            if (result == null || result.size() == 0) {
                break;
            }

            allPids.addAll(result);
            try {
                Thread.sleep((new Random().nextInt(5)+5)*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String[] headers = {"adzoneid","adzonePid","sitename","name"};
        List<List<String>> dataSet = new ArrayList<>();
        for (Pid pid : allPids) {
            List<String> list = new ArrayList<>();
            list.add(pid.getAdzoneid());
            list.add(pid.getAdzonePid());
            list.add(pid.getSitename());
            list.add(pid.getName());
            dataSet.add(list);
        }
        ExcelData excelData = new ExcelData("pids.xlsx","pids",headers,dataSet);
        try {
            ExcelUtil.poiExportExcel(excelData);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static Map<String,String> getCookies() {
        Map<String,String> cookies = new HashMap<>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\7_Full.txt")),
                    "UTF-8"));
            String lineTxt = null;
            while ((lineTxt = br.readLine()) != null) {
                if(lineTxt.contains("Cookie")){
                    lineTxt = lineTxt.replace("Cookie:","");
                    String[] strs = lineTxt.split(";");
                    for (String str : strs) {
                        String[] kv = str.split("=");
                        cookies.put(kv[0].trim(),kv[1].trim());
                    }
                }
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cookies;
    }

    public static List<Pid> getPids(Map<String,String> cookiemap,Map<String, String> nvps) {
        CookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore)
                .build();
        List<Pid> rs = new ArrayList<>();
        try {
            String url = "http://pub.alimama.com/common/adzone/adzoneManage.json";
            for (String k : cookiemap.keySet()) {
                BasicClientCookie cookie = new BasicClientCookie(k,cookiemap.get(k));
                cookie.setVersion(0);
                cookie.setDomain(".alimama.com");   //设置范围
                cookie.setPath("/");
                cookieStore.addCookie(cookie);
            }
            List<NameValuePair> nvpsList = new ArrayList<NameValuePair>();
            if(nvps != null){
                for (String key : nvps.keySet()) {
                    nvpsList.add(new BasicNameValuePair(key, nvps.get(key)));
                }
            }
            String connectUrl = HttpUtil.buildGetUrl(url, nvpsList);
            HttpGet httpGet = new HttpGet(connectUrl);
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(REQUEST_TIMEOUT).setConnectTimeout(CONNECTION_TIMEOUT).build();
            httpGet.setConfig(requestConfig);
            HttpResponse response = httpClient.execute(httpGet);//
            System.out.println(response.toString());
            if (response.getStatusLine().getStatusCode() == 200) {
                try {
                    HttpEntity res = response.getEntity();
                    String strs = EntityUtils.toString(res);
                    JSONObject jsonObject = JSON.parseObject(strs);
                    rs = JSON.parseArray(jsonObject.getJSONObject("data").getString("pagelist"), Pid.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{

        }
        return rs;
    }
}
